package com.kfm.common.domain.model;

import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.kfm.common.domain.entity.User;
import com.kfm.common.domain.serial.GrantedAuthorityDeserializer;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.io.Serializable;
import java.util.Collection;
import java.util.Set;

/**
 * 登录用户
 */
@Data
@NoArgsConstructor
public class LoginUser implements UserDetails, Serializable {

    private Long id;

    private String password;
    /**
     * 用户唯一标识
     */
    private String token;
    /**
     * 登录时间
     */
    private Long loginTime;
    /**
     * 过期时间
     */
    private Long expireTime;
    /**
     * 登录IP地址
     */
    private String ipaddr;
    /**
     * 登录地点
     */
    private String loginLocation;

    /**
     * 权限列表
     * permissions 是一个权限集合，可以用于存储用户的权限信息
     */
    @JsonDeserialize(using = GrantedAuthorityDeserializer.class)
    private Set<? extends GrantedAuthority> authorities;

    /**
     * 用户信息
     */
    private User user;

    public LoginUser(User user, Set<SimpleGrantedAuthority> authorities) {
        this.user = user;
        this.authorities = authorities;
    }

    public LoginUser(Long userId, User user, Set<SimpleGrantedAuthority> authorities) {
        this.id = userId;
        this.user = user;
        this.authorities = authorities;
    }

    @Override
    public String getUsername() {
        return user.getUsername();
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return authorities;
    }

    /**
     * 账户是否未过期,过期无法验证
     */
    @JSONField(serialize = false)
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    /**
     * 指定用户是否解锁,锁定的用户无法进行身份验证
     */
    @JSONField(serialize = false)
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    /**
     * 指示是否已过期的用户的凭据(密码),过期的凭据防止认证
     */
    @JSONField(serialize = false)
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    /**
     * 是否可用 ,禁用的用户不能身份验证
     */
    @JSONField(serialize = false)
    @Override
    public boolean isEnabled() {
        return true;
    }

    public boolean isAdmin() {
        return user.isAdmin();
    }
}
